//
//  PhotoBrowserViewController.swift
//  TYHWeibo
//
//  Created by IOS on 15/8/18.
//  Copyright © 2015年 IOS. All rights reserved.
//

import UIKit
import SVProgressHUD
private let TYHPhotoBrowserCell = "TYHPhotoBrowserCell"

class PhotoBrowserViewController: UIViewController {

    var urls: [NSURL]?
    var selectedIndex: Int
    
    init(urls: [NSURL], index: Int) {
        self.urls = urls
        selectedIndex = index
        
       super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    ///按钮监听方法
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    func save() {
//        print(__FUNCTION__)
        let indexPath = collectionView.indexPathsForVisibleItems().last!
        let cell = collectionView.cellForItemAtIndexPath(indexPath) as! PhotoBrowserCell
        
        guard let image = cell.imageView.image else {
            return
        }
        
        UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
    }
    
    //  - (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo;
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject?)
    {
        print(error)
        let msg = (error == nil) ? "保存成功" : "保存失败"
        SVProgressHUD.showInfoWithStatus(msg)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
//        print(urls)
        
        // Do any additional setup after loading the view.
    }
    
    override func loadView() {
        
        var screenBouns = UIScreen.mainScreen().bounds
        screenBouns.size.width += 20
        
        view = UIView(frame: screenBouns)
        setupUI()
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        
        let indexPath = NSIndexPath(forItem: selectedIndex, inSection: 0)
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.CenteredHorizontally, animated: false)
        
    }
    private func setupUI() {
        view.addSubview(collectionView)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        
        //自动布局
//        collectionView.translatesAutoresizingMaskIntoConstraints = false
//        closeButton.translatesAutoresizingMaskIntoConstraints = false
//        saveButton.translatesAutoresizingMaskIntoConstraints = false
//        
//        let dict = ["cv": collectionView, "close": closeButton, "save": saveButton]
        collectionView.frame = view.bounds
        
        let rect = CGRect(x: 0, y: UIScreen.mainScreen().bounds.height - 40, width: 100, height: 32)
        closeButton.frame = CGRectOffset(rect, 8, 0)
        saveButton.frame = CGRectOffset(rect, UIScreen.mainScreen().bounds.width - 108, 0)
        
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[close(32)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[save(32)]-0-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
//        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[close(100)]-(>=0)-[save(100)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: dict))
        
        closeButton.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        saveButton.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        prepareCollectionView()
        
    }
    
    private func prepareCollectionView() {
        collectionView.registerClass(PhotoBrowserCell.self, forCellWithReuseIdentifier: TYHPhotoBrowserCell)
        collectionView.dataSource = self
        
        let layout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        collectionView.pagingEnabled = true
        collectionView.showsHorizontalScrollIndicator = false
    }
    
    ///懒加载
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: UICollectionViewFlowLayout())
    private lazy var closeButton: UIButton = UIButton(title: "关闭", fontSize: 14, coler: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())
    private lazy var saveButton: UIButton = UIButton(title: "保存", fontSize: 14, coler: UIColor.whiteColor(), backColor: UIColor.darkGrayColor())

}

extension PhotoBrowserViewController: UICollectionViewDataSource {
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
           return urls!.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(TYHPhotoBrowserCell, forIndexPath: indexPath) as! PhotoBrowserCell
        cell.backgroundColor = UIColor.blackColor()
        cell.url = urls![indexPath.item]
        return cell
    }

}
